package com.itheima;

import com.sun.org.apache.bcel.internal.generic.NEW;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;

public class SpringApplicationContext {
    //创建静态map
    public static HashMap<String, Object> map;
    //初始化map
    static {
        map = new HashMap<String, Object>();
    }
    //    private Object obj;
    private String url;

    public SpringApplicationContext(String url) {
        this.url = url;
    }

    public Object getBean(String beanName) throws Exception {
        //创建解析器对象
        SAXReader sr = new SAXReader();
        //加载xml
        Document read = sr.read("src/main/resources/" + url);
        //获取根标签对象
        Element rootElement = read.getRootElement();
        //获取子标签
        List<Element> beans = rootElement.elements();
        for (Element bean : beans) {
            if (bean.attributeValue("id").equals(beanName)) {
                //获取class
                String aClass = bean.attributeValue("class");
                //使用反射创建对象
                Class<?> clazz = Class.forName(aClass);
                Object obj = clazz.newInstance();
                //获取set注入的子标签
                List<Element> elements = bean.elements();
                for (Element property : elements) {
                    //获取name
                    String name = property.attributeValue("name");
                    System.out.println("name = " + name);
                    //转发为方法名
                    String setName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
                    System.out.println("setName = " + setName);
                    //创建方法对象
                    Method method = clazz.getMethod(setName, name.getClass());
                    //获取value
                    String value = property.attributeValue("value");
                    System.out.println("value = " + value);
                    //使用方法
                    method.invoke(obj, value);
                }
                map.put(beanName, obj);
                return map.get(beanName);
            }
        }

        return null;
    }
}

